package com.quan.system.service.impl;

import com.quan.commons.core.MyBaseServiceImpl;
import com.quan.commons.utils.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.quan.system.commons.vo.SysLogVo;
import com.quan.system.entity.SysLog;
import com.quan.system.mapper.SysLogMapper;
import com.quan.system.service.SysLogService;


@Slf4j
@Service
public class SysLogServiceImpl extends MyBaseServiceImpl<SysLogMapper, SysLog> implements SysLogService {

    @Autowired
    private SysLogMapper mapper;

    @Override
    public List<SysLogVo> queryList(PageUtils pageUtils, SysLogVo vo) {
        QueryWrapper<SysLog> queryWrapper = new QueryWrapper<SysLog>(vo);

        List<SysLog> list = super.list(pageUtils, queryWrapper);
        List<SysLogVo> collect = list.stream().map(item -> {
                SysLogVo bean = new SysLogVo();
            BeanUtils.copyProperties(item, bean);
            return bean;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public PageUtils queryPage(PageUtils pageUtils, SysLogVo vo) {
        QueryWrapper<SysLog> queryWrapper = new QueryWrapper<SysLog>(vo);

        if (StringUtils.isNotBlank(vo.getKeyword())) {
            queryWrapper.and(w -> {
                w.like("user_name", vo.getKeyword())
                        .or().like("ip", vo.getKeyword())
                        .or().like("title", vo.getKeyword());
            });
        }

        final IPage<SysLog> page = super.selectPage(pageUtils, queryWrapper);

        PageUtils ps = new PageUtils(page);

        final List<SysLog> records = page.getRecords();

        final List<SysLog> collect = records.stream().map((item) -> {
            SysLogVo bean = new SysLogVo();
            BeanUtils.copyProperties(item, bean);
            return bean;
        }).collect(Collectors.toList());

        ps.setRecords(collect);
        return ps;
    }

    @Override
    public List<Long> totalLoginTimeReport() {

        List<Long> list = new ArrayList<Long>();

        int k = 0;
        for (int i = 0; i < 12; i++) {

            QueryWrapper<SysLog> queryWrapper = new QueryWrapper<SysLog>();
            queryWrapper.apply(" HOUR(ctime) >= {0} and HOUR(ctime) < {1}", k, k+2);
            list.add(super.count(queryWrapper));

            k = k + 2;
        }


        return list;
    }
}